using JGSY.CourseManagement.Domain.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using JGSY.CourseManagement.Presentation.Navigation;

namespace JGSY.CourseManagement.Infrastructure.Services
{
    /// <summary>
    /// 会话清理服务，定期清理过期会话并处理自动登出
    /// </summary>
    public class SessionCleanupService : BackgroundService
    {
        private readonly IUserSessionRepository _sessionRepository;
        private readonly INavigationService _navigationService;
        private readonly ILogger<SessionCleanupService> _logger;
        private readonly int _cleanupIntervalMinutes = 5;
        private readonly int _sessionTimeoutMinutes;

        public SessionCleanupService(
            IUserSessionRepository sessionRepository,
            INavigationService navigationService,
            ILogger<SessionCleanupService> logger,
            Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            _sessionRepository = sessionRepository ?? throw new ArgumentNullException(nameof(sessionRepository));
            _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _sessionTimeoutMinutes = int.Parse(configuration["AppSettings:SessionTimeoutMinutes"] ?? "30");
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("会话清理服务已启动，清理间隔: {Interval}分钟", _cleanupIntervalMinutes);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 清理过期会话
                    await _sessionRepository.CleanupExpiredSessionsAsync(stoppingToken);
                    _logger.LogDebug("已完成过期会话清理");

                    // 检查当前会话是否过期
                    var currentSession = await _sessionRepository.GetCurrentSessionAsync(cancellationToken: stoppingToken);
                    if (currentSession != null && currentSession.ExpireTime < DateTime.UtcNow)
                    {
                        _logger.LogInformation("检测到当前会话已过期，将导航至登录页");
                        await _navigationService.NavigateToAsync("LoginView");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "会话清理过程中发生错误");
                }

                // 等待下一次清理间隔
                await Task.Delay(TimeSpan.FromMinutes(_cleanupIntervalMinutes), stoppingToken);
            }

            _logger.LogInformation("会话清理服务已停止");
        }
    }
}